import express from "express";
import path from "path";
import { getIpAddress } from "@/utils/getIp";
import { clgLogStyles } from "@/utils/consoleLogStyle";
import fileRouter from "@/routes/api/operateFile";
import videoRouter from "./api/video";
import { PORT, staticPath } from "@/utils/const";
import loginRouter from "./api/login";
import uploadRouter from "./api/upload";
import { errorMiddleWare } from "./middleware/error";
import { WhiteList } from "../utils/const";
import cookieParser from "cookie-parser";
import { verifyIsLogin } from "./middleware/verifyIsLogin";
import { apiLogging } from "./middleware/apiLogger";
import downloadRouter from "./api/download";
import { exposeHeaders } from "./middleware/exposeHeaders";
import historyRouter from "./api/history";
import collectRouter from "./api/collect";
import favouriteRouter from "./api/favourite";
import captchaRouter from "./api/captcha";
import session from "express-session";
import { captchaHandler } from "./middleware/captchaMiddleware";
import { watchFile } from "../service/watchFile";

const cors = require("cors");
const app = express();

// 跨域配置白名单
var corsOptions = {
    origin: function (origin: string, callback: Function) {
        var originIsWhitelisted = WhiteList.indexOf(origin) !== -1;
        callback(null, originIsWhitelisted);
    },
};

app.use(
    session({
        secret: "shuaibo",
        name: "sessionId",
        resave: false,
        saveUninitialized: true,
    })
);
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(exposeHeaders);
// 管理静态资源
app.use(
    "/static",
    express.static(staticPath, {
        maxAge: "2h",
        immutable: true,
    })
);
app.use(
    "/static",
    express.static(path.resolve(__dirname, "../../static/"), {
        immutable: true,
        setHeaders(res, path) {
            if (!path.endsWith(".html")) {
                res.header("Cache-Control", `max-age=${3600}`);
            }
        },
    })
);

//解析json数据
app.use(express.json());
//解析urlencoded数据, x-www-form-urlencoded
app.use(express.urlencoded({ extended: false }));

// 记录日志
app.use(apiLogging());

// 判断是否是机器人，10秒内请求超过3次
app.use(captchaHandler);

// 通用接口， 无需登录
app.use("/api", loginRouter);
app.use("/captcha", captchaRouter);
// 验证是否登录
app.use(verifyIsLogin);

// 接口需要登录
app.use("/api/file", fileRouter);
app.use("/api/video", videoRouter);
app.use("/api/upload", uploadRouter);
app.use("/api/download", downloadRouter);
app.use("/api/history", historyRouter);
app.use("/api/collect", collectRouter);
app.use("/api/favourite", favouriteRouter);

// 错误处理中间件
app.use(errorMiddleWare);

const IP = getIpAddress();
app.listen(PORT, () => {
    console.log(clgLogStyles.blue, `server listen on IP:  http://${IP}:${PORT}`);
});
watchFile().then(() => {
    console.log("结束");
});
